package com.egao.common.module.cooperative.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egao.common.core.exception.BusinessException;
import com.egao.common.core.utils.CoreUtil;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.module.cooperative.constants.CooperativeProjectConstants;
import com.egao.common.module.cooperative.entity.CooperativeProject;
import com.egao.common.module.cooperative.entity.CooperativeProjectActivityStudent;
import com.egao.common.module.cooperative.entity.vo.CooperativeProjectActivityStudentListVO;
import com.egao.common.module.cooperative.mapper.CooperativeProjectActivityStudentMapper;
import com.egao.common.module.cooperative.service.CooperativeProjectActivityStudentService;
import com.egao.common.module.student.constants.StudentPovertyConstants;
import com.egao.common.module.student.entity.Student;
import com.egao.common.module.student.entity.StudentPoverty;
import com.egao.common.module.student.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 产教融合 学生活动接口实现
 *
 * @author root
 */
@Service
public class CooperativeProjectActivityStudentServiceImpl extends ServiceImpl<CooperativeProjectActivityStudentMapper, CooperativeProjectActivityStudent>
        implements CooperativeProjectActivityStudentService {

    @Autowired
    private StudentService studentService;

    @Override
    public List<CooperativeProjectActivityStudentListVO> listPage(PageParam<CooperativeProjectActivityStudent> page) {
        return baseMapper.listPage(page);
    }

    @Override
    public CooperativeProjectActivityStudent getById(Integer activityId, Integer studentId) {
        List<CooperativeProjectActivityStudent> list = baseMapper.selectList(new QueryWrapper<CooperativeProjectActivityStudent>()
                .eq("cooperative_project_activity_id", activityId)
                .eq("student_id", studentId)
                .orderByDesc("create_time")
        );

        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public Integer countApply(Integer activityId) {
        return baseMapper.selectCount(new QueryWrapper<CooperativeProjectActivityStudent>()
                .eq("state", CooperativeProjectConstants.CPAS_STATE_APPLY)
                .eq("cooperative_project_activity_id", activityId)
        );
    }

    @Override
    public List<CooperativeProjectActivityStudentListVO> listActivityPage(PageParam<CooperativeProjectActivityStudent> page) {
        return baseMapper.listActivityPage(page);
    }

    @Override
    public JsonResult apply(CooperativeProjectActivityStudent cooperativeProjectActivityStudent) {
        int count = baseMapper.selectCount(new QueryWrapper<CooperativeProjectActivityStudent>()
                .eq("cooperative_project_activity_id", cooperativeProjectActivityStudent.getCooperativeProjectActivityId())
                .eq("student_id", cooperativeProjectActivityStudent.getStudentId())
        );
        if (count > 0) {
            return JsonResult.error("已报名");
        }

        cooperativeProjectActivityStudent.setState(CooperativeProjectConstants.CPAS_STATE_APPLY);
        cooperativeProjectActivityStudent.setStateDate(new Date());
        cooperativeProjectActivityStudent.setSign(CooperativeProjectConstants.CPAS_SIGN_NO);
        if (save(cooperativeProjectActivityStudent)) {
            return JsonResult.ok("报名成功");
        }

        return JsonResult.error("报名失败");
    }

    @Override
    public JsonResult cancel(CooperativeProjectActivityStudent cooperativeProjectActivityStudent) {
        CooperativeProjectActivityStudent activityStudent = getById(cooperativeProjectActivityStudent.getId());

        // 重复取消不记录本次操作返回取消成功
        if (CooperativeProjectConstants.CPAS_STATE_CANCEL.equals(activityStudent.getState())) {
            return JsonResult.ok("取消成功");
        }

        activityStudent.setState(CooperativeProjectConstants.CPAS_STATE_CANCEL);
        activityStudent.setCancel(cooperativeProjectActivityStudent.getCancel());
        activityStudent.setCancelDate(new Date());
        if (updateById(activityStudent)) {
            return JsonResult.ok("取消成功");
        }

        return JsonResult.error("取消失败");
    }

    @Override
    public JsonResult importStudent(MultipartFile file, Integer cooperativeProjectActivityId) {
        if (null == cooperativeProjectActivityId) {
            throw new BusinessException("活动参数异常");
        }

        StringBuilder sb = new StringBuilder();
        try {
            // 读取Excel
            int startRow = 1;
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream(), 0);
            List<List<Object>> list = reader.read(startRow);

            // 进行非空和重复检查
            sb.append(CoreUtil.excelCheckBlank(list, startRow, 0));
            sb.append(CoreUtil.excelCheckRepeat(list, startRow, 0));
            if (!sb.toString().isEmpty()) {
                return JsonResult.error(sb.toString());
            }

            List<String> xhList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                List<Object> objects = list.get(i);
                String xh = String.valueOf(objects.get(0));
                xhList.add(xh);
            }

            xhList = xhList.stream().distinct().collect(Collectors.toList());
            List<Integer> studentIds = studentService.listObjs(new QueryWrapper<Student>().lambda()
                            .select(Student::getId)
                            .in(Student::getXh, xhList),
                    d -> Integer.parseInt(d.toString())
            );

            UpdateWrapper<CooperativeProjectActivityStudent> uw = new UpdateWrapper<>();
            uw.lambda()
                    .set(CooperativeProjectActivityStudent::getSign, CooperativeProjectConstants.CPAS_SIGN_YES)
                    .set(CooperativeProjectActivityStudent::getSignDate, new Date())
                    .eq(CooperativeProjectActivityStudent::getCooperativeProjectActivityId, cooperativeProjectActivityId)
                    .in(CooperativeProjectActivityStudent::getStudentId, studentIds);

            update(uw);
            return JsonResult.ok("导入完成");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return JsonResult.error("导入失败");
    }
}
